package com.logic.system.service.impl;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.logic.common.exception.BusinessException;
import com.logic.landseaserver.common.enums.WeChatMsgEnum;
import com.logic.landseaserver.common.util.HttpRequestClient;
import com.logic.landseaserver.common.util.WeChatUtil;
import com.logic.system.domain.WeChatUser;
import com.logic.system.persistence.read.OrganizationReadMapper;
import com.logic.system.persistence.write.OrganizationWriteMapper;
import com.logic.system.service.IWeChatService;
import com.logic.system.ws.dto.WeChatCorporateDTO;

import net.sf.json.JSONObject;

@Service
public class WeChatService implements IWeChatService {
	@Autowired
	OrganizationWriteMapper orgWriteMapper;
	
	@Autowired
	OrganizationReadMapper orgReadMapper;
	
	Logger logger = LoggerFactory.getLogger(WeChatService.class);
	private static String CORPBT = "WBT0";
	private static String LOGIBT = "WBT1";
	private String access_token = null;
	private String login_access_token = null;
	private static String ADD_CORP_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=";
	private static String UPDATE_CORP_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=";
	private static String CORPLIST_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/list";
	private static String ADD_USER_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=";
	private static String DELETE_CORP_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=";
	private static String CORP_LIST_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=";
	private static String UPDATE_USER_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=";
	private static String DELETE_USER_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=ACCESS_TOKEN&userid=USERID";
	private static String BATCH_DELETE_USER_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=ACCESS_TOKEN";
	private static String GET_USER_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID";
	private static String GET_CORP_USERS_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?";
	private static String GET_USER_BY_CODE_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE";

	private void validateToken(String businessType) {
		WeChatUtil wechatutil = WeChatUtil.getInstance();
		if("WBT0".equals(businessType)){
			try {
				access_token = wechatutil.getAccessToken(businessType);
			} catch (ParseException e) {
			    logger.error("validateToken error.", e);
			}
		}else if("WBT1".equals(businessType)){
			try {
				login_access_token = wechatutil.getAccessToken(businessType);
			} catch (ParseException e) {
			    logger.error("validateToken error.", e);
			}
		}
		
	}

	//创建组织
	@Override
	public String createCorperate(HashMap map) throws Exception {
		validateToken(CORPBT);
		String body = "{"+
				   "\"name\": \""+map.get("name")+"\","+
				   "\"parentid\": "+map.get("parentid")+""+
				"}";
		logger.info("WeChatService | createCorperate wechat body: "+body);
		String result = HttpRequestClient.postHttpsRequest(ADD_CORP_URL+access_token, body);
		logger.info("WeChatService | createCorperate wechat response: "+result);
		checkWeChatResult(result);
		return result;
	}

	//删除组织
	@Override
	public String deleteCorperate(int corpId) throws Exception {
		validateToken(CORPBT);
		Map<String, String> headMap = new HashMap<String,String>();
		headMap.put("Access-Control-Allow-Origin", "*");
        headMap.put("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        headMap.put("Access-Control-Max-Age", "3600");
        headMap.put("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        headMap.put("Access-Control-Expose-Headers", "MSG, STATUS, COUNT, TOTAL_COUNT, USER_ID, USER_NAME, ORG_ID, size, context, token");
        logger.info("WeChatService | deleteCorperate wechat url: "+DELETE_CORP_URL+"access_token"+"&id="+corpId);
        String result = HttpRequestClient.getRequest(DELETE_CORP_URL+access_token+"&id="+corpId, headMap);
		logger.info("WeChatService | deleteCorperate wechat response: "+result);
		checkWeChatResult(result);
		return result;
	}

	//更新部门
	@Override
	public String updateCorperate(WeChatCorporateDTO corperate) throws BusinessException {
		validateToken(CORPBT);
		String body = corperate.toString();
		logger.info("WeChatService | updateCorperate wechat body: "+body);
		String result = HttpRequestClient.postHttpsRequest(UPDATE_CORP_URL+access_token, body);
		logger.info("WeChatService | updateCorperate wechat response: "+result);
		checkWeChatResult(result);
		return result;
	}


	//查询部门列表
	@Override
	public String getCorperateList() throws Exception {
		validateToken(CORPBT);
		Map<String, String> headMap = new HashMap<String,String>();
		headMap.put("Access-Control-Allow-Origin", "*");
        headMap.put("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        headMap.put("Access-Control-Max-Age", "3600");
        headMap.put("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        headMap.put("Access-Control-Expose-Headers", "MSG, STATUS, COUNT, TOTAL_COUNT, USER_ID, USER_NAME, ORG_ID, size, context, token");
        logger.info("WeChatService | getCorperateList wechat url: "+CORP_LIST_URL+"access_token");
        String result = HttpRequestClient.getRequest(CORP_LIST_URL+access_token, headMap);
		logger.info("WeChatService | getCorperateList wechat response: "+result);
		checkWeChatResult(result);
		return result;
	}
	
	//查询部门列表
	@Override
	public String getCorperateListById(int id) throws Exception {
		validateToken(CORPBT);
		Map<String, String> headMap = new HashMap<String,String>();
		headMap.put("Access-Control-Allow-Origin", "*");
        headMap.put("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        headMap.put("Access-Control-Max-Age", "3600");
        headMap.put("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        headMap.put("Access-Control-Expose-Headers", "MSG, STATUS, COUNT, TOTAL_COUNT, USER_ID, USER_NAME, ORG_ID, size, context, token");
        logger.info("WeChatService | getCorperateListById wechat url: "+CORP_LIST_URL+"access_token"+"&id="+id);
        String result = HttpRequestClient.getRequest(CORP_LIST_URL+access_token+"&id="+id, headMap);
		logger.info("WeChatService | getCorperateListById wechat response: "+result);
		checkWeChatResult(result);
		return result;
	}


	//添加成员
	@Override
	public String addUser(WeChatUser user) throws Exception {
		validateToken(CORPBT);
		String userbody = user.toString();
		logger.info("WeChatService | addUser wechat body: "+userbody);
		String result = HttpRequestClient.postHttpsRequest(ADD_USER_URL+access_token, userbody);
		logger.info("WeChatService | addUser wechat response: "+result);
		// 暂时处理不能影响流程继续下走 Updated by Daniel on 20170625
		try{
			checkWeChatResult(result);
		} catch(BusinessException e){
		    logger.error("addUser error.", e);
		}
		return result;
	}


	//更新成员
	@Override
	public String updateUser(WeChatUser user) throws Exception {
		validateToken(CORPBT);
		String userbody = user.toString();
		logger.info("WeChatService | updateUser wechat body: "+userbody);
		String result = HttpRequestClient.postHttpsRequest(UPDATE_USER_URL+access_token, userbody);
		logger.info("WeChatService | updateUser wechat response: "+result);
		// 暂时处理不能影响流程继续下走 Updated by Daniel on 20170625
		try{
			checkWeChatResult(result);
		} catch(BusinessException e){
		    logger.error("updateUser error.", e);
		}
		return result;
	}

	//删除成员
	@Override
	public String deleteUser(int userid) throws Exception {
		validateToken(CORPBT);
		Map<String, String> headMap = new HashMap<String,String>();
		headMap.put("Access-Control-Allow-Origin", "*");
        headMap.put("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        headMap.put("Access-Control-Max-Age", "3600");
        headMap.put("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        headMap.put("Access-Control-Expose-Headers", "MSG, STATUS, COUNT, TOTAL_COUNT, USER_ID, USER_NAME, ORG_ID, size, context, token");
		String url = DELETE_USER_URL.replace("ACCESS_TOKEN", access_token).replace("USERID", userid+"");
		logger.info("WeChatService | deleteUser wechat url: "+url);
		String result = HttpRequestClient.getRequest(url, headMap);
        logger.info("WeChatService | deleteUser wechat response: "+result);
		// 暂时处理不能影响流程继续下走 Updated by Daniel on 20170625
		try{
			checkWeChatResult(result);
		} catch(BusinessException e){
		    logger.error("deleteUser error.", e);
		}
		return result;
	}

	//批量删除
	@Override
	public String batchDelete(List<String> parem) throws Exception {
		validateToken(CORPBT);
		JSONObject json = new JSONObject();
		json.put("useridlist", parem);
		String url = BATCH_DELETE_USER_URL.replace("ACCESS_TOKEN", access_token);
		logger.info("WeChatService | batchDelete wechat body: "+json.toString());
        String result = HttpRequestClient.postHttpsRequest(url, json.toString());
        logger.info("WeChatService | batchDelete wechat response: "+result);
		// 暂时处理不能影响流程继续下走 Updated by Daniel on 20170625
		try{
			checkWeChatResult(result);
		} catch(BusinessException e){
		    logger.error("batchDelete error.", e);
		}
		return result;
	}

	//获取成员信息
	@Override
	public String getUser(int userid) throws Exception {
		validateToken(CORPBT);
		Map<String, String> headMap = new HashMap<String,String>();
		headMap.put("Access-Control-Allow-Origin", "*");
        headMap.put("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        headMap.put("Access-Control-Max-Age", "3600");
        headMap.put("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        headMap.put("Access-Control-Expose-Headers", "MSG, STATUS, COUNT, TOTAL_COUNT, USER_ID, USER_NAME, ORG_ID, size, context, token");
		String url = GET_USER_URL.replace("ACCESS_TOKEN", access_token).replace("USERID", userid+"");
		logger.info("WeChatService | getUser wechat USERID: "+userid);
		String result = HttpRequestClient.getRequest(url, headMap);
        logger.info("WeChatService | getUser wechat response: "+result);
		// 暂时处理不能影响流程继续下走 Updated by Daniel on 20170625
		try{
			checkWeChatResult(result);
		} catch(BusinessException e){
		    logger.error("getUser error.", e);
		}
		return result;
	}


	@Override
	public String getCorpUsers(HashMap map) throws Exception {
		validateToken(CORPBT);
		Map<String, String> headMap = new HashMap<String,String>();
		headMap.put("Access-Control-Allow-Origin", "*");
        headMap.put("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        headMap.put("Access-Control-Max-Age", "3600");
        headMap.put("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        headMap.put("Access-Control-Expose-Headers", "MSG, STATUS, COUNT, TOTAL_COUNT, USER_ID, USER_NAME, ORG_ID, size, context, token");
		StringBuffer url = new StringBuffer(GET_CORP_USERS_URL);
		url.append("access_token="+access_token);
		url.append("&department_id  ="+map.get("department_id"));
        if(map.containsKey("fetch_child")){
        	url.append("&fetch_child="+map.get("fetch_child"));
        }
        if(map.containsKey("status")){
        	url.append("&status="+map.get("status"));
        }
//        logger.info("WeChatService | getCorpUsers wechat url: "+url.toString());
		String result = HttpRequestClient.getRequest(url.toString(), headMap);
		logger.info("WeChatService | getCorpUsers wechat response: "+result);
		// 暂时处理不能影响流程继续下走 Updated by Daniel on 20170625
		try{
			checkWeChatResult(result);
		} catch(BusinessException e){
		    logger.error("getCorpUsers error.", e);
		}
		return result;
	}

	@Override
	public String getUserInfoByCode(String code) throws Exception {
		logger.info("微信登陆接口调用");
		validateToken(LOGIBT);
		Map<String, String> headMap = new HashMap<String,String>();
		headMap.put("Access-Control-Allow-Origin", "*");
        headMap.put("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        headMap.put("Access-Control-Max-Age", "3600");
        headMap.put("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        headMap.put("Access-Control-Expose-Headers", "MSG, STATUS, COUNT, TOTAL_COUNT, USER_ID, USER_NAME, ORG_ID, size, context, token");
		String url = GET_USER_BY_CODE_URL.replace("ACCESS_TOKEN", login_access_token).replace("CODE", code);
		logger.info("WeChatService | getUserInfoByCode wechat CODE: "+code);
		String result = HttpRequestClient.getRequest(url, headMap);
        logger.info("WeChatService | getUserInfoByCode wechat response: "+result);
        // 暂时处理不能影响流程继续下走 Updated by Daniel on 20170625
        try{
			checkWeChatResult(result);
		} catch(BusinessException e){
		    logger.error("getUserInfoByCode error.", e);
		}

		return result;
	}


	public String checkWeChatResult(String result) throws BusinessException{
		JSONObject resultobj = JSONObject.fromObject(result);
		if(resultobj.containsKey("errcode")){
			if(!"0".equals(resultobj.getString("errcode"))){
				String errormsg = null;
				if("-1".equals(resultobj.getString("errcode"))){
					errormsg = WeChatMsgEnum.valueOf("_1").getCode();
				}else{
					errormsg = WeChatMsgEnum.valueOf("_"+resultobj.getString("errcode")).getCode();
				}
				logger.error("微信端错误："+ errormsg+"   ",this.getClass());
				throw new BusinessException("微信端错误："+errormsg);
			}
		}
		return result;
	}
	
	
}
